package com.coder.oj.admin.config;

import com.coder.oj.common.core.BaseContext;
import com.coder.oj.common.entity.*;
import com.coder.oj.common.enums.CommonStatusEnum;
import com.coder.oj.common.exception.DataException;
import com.coder.oj.common.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 权限拦截器
 * @author Bosen 2022/11/29 14:42
 */
@Component
public class RbacHandlerInterceptor implements HandlerInterceptor {

    private static AdminMapper adminMapper;

    private static RoleMapper roleMapper;

    private static OauthMapper oauthMapper;

    private static AdminRoleMapper adminRoleMapper;

    private static RoleOauthMapper roleOauthMapper;

    @Autowired
    public void setAdminMapper(AdminMapper adminMapper) {
        RbacHandlerInterceptor.adminMapper = adminMapper;
    }

    @Autowired
    public void setRoleMapper(RoleMapper roleMapper) {
        RbacHandlerInterceptor.roleMapper = roleMapper;
    }

    @Autowired
    public void setOauthMapper(OauthMapper oauthMapper) {
        RbacHandlerInterceptor.oauthMapper = oauthMapper;
    }

    @Autowired
    public void setAdminRoleMapper(AdminRoleMapper adminRoleMapper) {
        RbacHandlerInterceptor.adminRoleMapper = adminRoleMapper;
    }

    @Autowired
    public void setRoleOauthMapper(RoleOauthMapper roleOauthMapper) {
        RbacHandlerInterceptor.roleOauthMapper = roleOauthMapper;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!checkRbac(request)) {
            throw new DataException(403, "无访问权限");
        }
        return true;
    }

    /**
     * 检查权限
     * @author Bosen 2022/11/29 14:46
     */
    private boolean checkRbac(HttpServletRequest request) {
        try {
            // 获取当前请求的地址
            String curUrl = request.getRequestURI();
            // 获取当前管理员的信息
            Admin admin = adminMapper.selectById(BaseContext.getCurrentId());
            // 不限制Admin
            if(CommonStatusEnum.getEnum(admin.getIsAdmin()) == CommonStatusEnum.ENABLED) {
                return true;
            }
            // 获取角色信息
            List<AdminRole> adminRoles = adminRoleMapper.selectByAdminId(admin.getId());
            if(!CollectionUtils.isEmpty(adminRoles)) {
                List<Role> roles = adminRoles.stream().map(adminRole ->
                        roleMapper.selectById(adminRole.getRoleId())).collect(Collectors.toList());
                for(Role role : roles) {
                    // 过滤禁用角色
                    if(CommonStatusEnum.getEnum(role.getStatus()) == CommonStatusEnum.DISABLED) {
                        continue;
                    }
                    // 获取权限信息
                    List<RoleOauth> roleAccessList = roleOauthMapper.selectByRoleId(role.getId());
                    for (RoleOauth roleOauth : roleAccessList) {
                        Oauth oauth = oauthMapper.selectById(roleOauth.getOauthId());
                        if(CommonStatusEnum.getEnum(oauth.getStatus()) == CommonStatusEnum.DISABLED) {
                            continue;
                        }
                        if (oauth.getMark().equals(curUrl)
                                && request.getMethod().equals(oauth.getRest())
                                && CommonStatusEnum.getEnum(oauth.getStatus()) == CommonStatusEnum.ENABLED) {
                            return true;
                        }
                    }
                }
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }
}
